package cn.ante.ymcc.service.impl;

import cn.ante.ymcc.domain.Login;
import cn.ante.ymcc.dto.LoginParamDto;
import cn.ante.ymcc.dto.RefreshTokenDto;
import cn.ante.ymcc.mapper.LoginMapper;
import cn.ante.ymcc.result.JSONResult;
import cn.ante.ymcc.service.ILoginService;
import cn.ante.ymcc.util.AssertUtil;
import cn.ante.ymcc.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author Nai
 * @since 2022-08-05
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    @Autowired
    private ILoginService loginService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public boolean insert(Login entity) {
        return super.insert(entity);
    }

    // 账号密码生成token连接
    private static final String TOKEN_URL = "http://localhost:10030/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&redirect_uri=http://www.baidu.com&password=%s";

    // 刷新token地址
    private static final String REFRESH_TOKEN_URL = "http://localhost:10030/oauth/token?grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s";
    /**
    * @Description: 登录认证生成token        http://localhost:10030/oauth/token?grant_type=refresh_token&refresh_token=
    * @Author: Nai
    * @Version: 1.0
    * @Date:  2022/8/28 0:42
    */
    @Override
    public JSONResult loginSuccess(LoginParamDto dto) {
        Integer type = dto.getType();
        String clientId = null;
        String secret = null;
        // 根据门户和后台拼接不同的客户端
        if (type == 0 ){
            // 拼接管理后台客户端
            clientId = "admin";
            secret = "123";
        }else if (type == 1){
            // 拼接管理前台客户端
            clientId = "website";
            secret = "123";
        }
        AssertUtil.isNotNull(clientId,"非法请求");
        // 拿到生成token
        String tokenUrl = String.format(TOKEN_URL,clientId,secret,dto.getUsername(),dto.getPassword());
        // 拼接号账号密码获取token链接
        String result = HttpUtil.sendPost(tokenUrl, null);
        Map map = JSONObject.parseObject(result, Map.class);
        if(result.contains("error_description")){
            return JSONResult.error("用户或密码错误");
        }
        //设置token的过期时间
        map.put("expiresTime",System.currentTimeMillis() + Long.valueOf(map.get("expires_in").toString()));
        return JSONResult.success(map);
    }

    @Override
    public JSONResult refreshToken(RefreshTokenDto dto) {
        Login login = loginService.selectByUsername(dto.getUsername());
        AssertUtil.isNotNull(login,"登录失效");
        //拼接刷新Token的URL
        String tokenUrl = String.format(REFRESH_TOKEN_URL, dto.getRefreshToken(),login.getClientId(), login.getClientSecret());

        //发送Http请求
        String tokenJSON = HttpUtil.sendPost(tokenUrl, null);

        Map accessToken = JSON.parseObject(tokenJSON, Map.class);

        return JSONResult.success(accessToken);
    }

    @Override
    public Login selectByUsername(String username) {
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",username);
        return loginService.selectOne(wrapper);
    }
}
